using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.WorkOrder;
using B.S.XZYData.Api.Read.Dto.WorkOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.WorkOrder
{
    /// <summary>
    /// 获取工序选择列表处理器
    /// </summary>
    public class GetRouteStepSelectHandler : IRequestHandler<GetRouteStepSelectCommand, ApiPageing<RouteStepSelectDto>>
    {
        private readonly IBaseRepository<WorkOrderProcessModel> _workOrderProcessRepo;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workOrderProcessRepo">工单工序仓储</param>
        /// <param name="mapper">AutoMapper</param>
        public GetRouteStepSelectHandler(
            IBaseRepository<WorkOrderProcessModel> workOrderProcessRepo,
            IMapper mapper)
        {
            _workOrderProcessRepo = workOrderProcessRepo;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取工序选择列表请求
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>工序选择列表</returns>
        public Task<ApiPageing<RouteStepSelectDto>> Handle(GetRouteStepSelectCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<RouteStepSelectDto>();

            try
            {
                // 构建查询条件
                var query = _workOrderProcessRepo.GetAll();

                // 工序编号模糊查询
                if (!string.IsNullOrWhiteSpace(request.ProcessCode))
                {
                    query = query.Where(x => x.ProcessCode.Contains(request.ProcessCode));
                }

                // 工序名称模糊查询
                if (!string.IsNullOrWhiteSpace(request.ProcessName))
                {
                    query = query.Where(x => x.ProcessName.Contains(request.ProcessName));
                }

                // 获取所有符合条件的工序
                var allProcesses = query.ToList();

                // 在内存中按工序编号和名称去重
                var distinctProcesses = allProcesses
                    .GroupBy(x => new { x.ProcessCode, x.ProcessName })
                    .Select(g => g.First())
                    .OrderBy(x => x.ProcessCode)
                    .ThenBy(x => x.ProcessName)
                    .ToList();

                // 获取总数
                var totalCount = distinctProcesses.Count;

                // 分页
                var workOrderProcesses = distinctProcesses
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();

                // 手动映射到DTO（因为WorkOrderProcessModel和RouteStepSelectDto字段不完全匹配）
                var routeStepDtos = workOrderProcesses.Select(x => new RouteStepSelectDto
                {
                    Id = x.Id,
                    RouteId = 0, // WorkOrderProcessModel没有RouteId，设置为0
                    Sequence = x.Sequence,
                    ProcessCode = x.ProcessCode,
                    ProcessName = x.ProcessName,
                    Ratio = x.Ratio,
                    Type = null // WorkOrderProcessModel没有Type字段
                }).ToList();

                res.PageData = routeStepDtos;
                res.TotaCount = totalCount;
                res.TotaPage = (int)Math.Ceiling((double)totalCount / request.Size);
                res.Code = ApiEnum.Success;
                res.Msg = "获取工序选择列表成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取工序选择列表失败：{ex.Message}";
            }

            return Task.FromResult(res);
        }
    }
}
